<script src="../node_modules/vue/dist/vue.js"></script>
<script src="./path-to-regexp.js"></script>

<div id="app"></div>

<script>
  // '#/foo/123' -> foo with id: 123
  // '#/bar' -> Bar
  // '#/404' -> NotFound

  // path-to-regexp usage:
  const pattern = '/foo/:id'
  const keys = []
  const regex = pathToRegexp(pattern, keys)
  // console.log(keys.map(key => key.name))

  const incomingPath = '/foo/123'
  const match = regex.exec(incomingPath)
  // console.log(match)
  const params = {}
  keys.forEach((key, index) => {
    params[key.name] = match[index + 1]
  })
  console.log(params)

  const Foo = {
    props: ['id'],
    template: `<div>foo with id: {{ id }}</div>`
  }
  const Bar = { template: `<div>bar</div>` }
  const NotFound = { template: `<div>not found!</div>` }

  const routeTable = {
    '/foo/:id': Foo,
    '/bar': Bar
  }

  // pre-compile patterns into regex
  const compiledRouteTable = {}
  Object.keys(routeTable).forEach(pattern => {
    const dynamicSegments = []
    compiledRouteTable[pattern] = {
      component: routeTable[pattern],
      regex: pathToRegexp(pattern, dynamicSegments),
      dynamicSegments
    }
  })

  window.addEventListener('hashchange', () => {
    // Implement this!
    app.url = window.location.hash.slice(1)
  })

  const app = new Vue({
    el: '#app',
    data: {
      url: window.location.hash.slice(1)
    },
    render(h) {
      const path = '/' + this.url

      let componentToRender
      let props = {}

      // Implement the logic to figure out proper values
      // for componentToRender and props

      Object.keys(compiledRouteTable).some(pattern => {
        const { component, regex, dynamicSegments } = compiledRouteTable[pattern]
        const match = regex.exec(path)
        if (match) {
          // we have a match!
          componentToRender = component
          dynamicSegments.forEach(({ name }, index) => {
            props[name] = match[index + 1]
          })
          return true
        }
      })

      return h('div', { attrs: { id: 'app' } }, [
        h(componentToRender || NotFound, {
          props
        }),
        h('a', { attrs: { href: '#foo/123' } }, 'foo/123'),
        ' | ',
        h('a', { attrs: { href: '#bar' } }, 'bar')
      ])
    }
  })
</script>